package org.theonept.travian.t4a.village;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.theonept.travian.model.Compte;
import org.theonept.travian.model.Ressource;
import org.theonept.travian.model.Village;
import org.theonept.travian.t4a.R;
import org.theonept.travian.t4a.ressource.RessourcesSectionFragment;
import org.theonept.travian.util.AsyncWeb;
import org.theonept.travian.util.T4AUtil;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;

public class VillageActivity extends FragmentActivity {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	private Village village;
	private Compte compte;
	private RessourcesSectionFragment fragmentRessource;
	public Object villageAsync;

	public ArrayList<Ressource> ressources;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// This has to be called before
		// setContentView
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_village);

		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
		village = (Village) getIntent().getExtras().getSerializable("village");
		compte = (Compte) getIntent().getExtras().getSerializable("compte");
		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		villageAsync = new VillageAsync(compte).execute();
		T4AUtil.setTextViewRessources(VillageActivity.this, village.getProduction(false));

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.compte, menu);
		menu.findItem(R.id.action_refresh);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_refresh:
			// This shows an indeterminate progress bar in the action bar
			if (villageAsync == null) {
				villageAsync = new VillageAsync(compte).execute(compte);
				return true;
			} else {
				return false;
			}
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			fin();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void fin() {
		setResult(RESULT_OK, getIntent());
		finish();
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			fragmentRessource = new RessourcesSectionFragment();
			Bundle args = new Bundle();
			args.putSerializable("compte", compte);
			args.putSerializable("village", village);

			fragmentRessource.setArguments(args);
			return fragmentRessource;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 1;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section_ressource).toUpperCase(l);
			}
			return null;
		}
	}

	class VillageAsync extends AsyncWeb<Compte, Void, Boolean> {

		public VillageAsync(Compte compte) {
			super(compte);
			// TODO Auto-generated constructor stub
		}

		@Override
		protected void onCancelled() {
			villageAsync = null;
			setProgressBarIndeterminateVisibility(false);

			super.onCancelled();
		}

		@Override
		protected void onPreExecute() {
			setProgressBarIndeterminateVisibility(true);

			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				if (fragmentRessource != null) {
					fragmentRessource.setData(ressources);
					fragmentRessource.getArguments().putSerializable("ressources", ressources);
				}
				T4AUtil.setTextViewRessources(VillageActivity.this, village.getProduction(false));
			} else {
				finish();
			}

			villageAsync = null;
			setProgressBarIndeterminateVisibility(false);
			super.onPostExecute(result);
		}

		@Override
		protected Boolean executeWebTask(Compte... params) {

			// TODO Auto-generated method stub
			if (compte.isEtat(true, true)) {

				List<Ressource> ressources = village.getProduction(true).getRessources();
				VillageActivity.this.ressources = (ArrayList<Ressource>) ressources;
				return true;
			}
			return false;
		}

	}

	@Override
	protected void onResume() {
		villageAsync = new VillageAsync(compte).execute();
		super.onResume();
	}
}
